var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//引入数据库的配置信息
var settings=require('./settings');
//加载路由的文件，在这里相当于MVC中的控制器
var routers = require('./routes/index');
//加载connect-flash模块，进行信息的提示，只会提示一次
var flash=require('connect-flash');
//在服务端的支持会话
var session=require('express-session');
//将会话信息保存到数据库
var MongoStore=require('connect-mongo')(session);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 存放logo角标的图片
app.use(favicon(path.join(__dirname, 'public/zhihuLogo', 'zhihuLogo.jpg')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(session({
    //防止篡改cookie的信息
    secret:settings.cookieSecret,
    //设置值
    key:settings.db,
    //生命周期30天
    cookie:{MaxAge:30*24*60*60*1000},
    //将session的信息存储到数据库
    store:new MongoStore({
        //数据库的地址
        url:'mongodb://localhost/zhihu'
    }),
    //为true时，每次存储会话信息时，都会重新设置生命周期
    resave:false,
    //为true时，保持之前的设置，不在进行初始化
    saveUninitialized:true
}));
//这句代码一定要在app.use(bodyParser....)后面使用，否则报错
routers(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

//添加监听端口
app.listen(3000,function () {
    console.log('the server is running.');
})

module.exports = app;
